import {OssUrl,secret} from '@/config/index.js'



/**
 * 提取富文本中的文字
 * @param {*} html 
 */
function getSimpleText(html) {
	let re1 = new RegExp('<.+?>', 'g')
	return html.replace(re1, '').replace('&nbsp;', '')
}



/**
 * 提取文件名的扩展名
 * @param {*} fileName 
 */
function getFileNameExt(fileName) {
	let index = String(fileName).lastIndexOf('.');
	if (index < 0) {
		return
	}
	return fileName.slice(index + 1)
}

/**
 * 验证手机号码
 * @param {Object} phone 
 */
const checkPhone = function(phone) {
	if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone))) {
		return false; //不满足条件
	} else {
		return true; //满足条件
	}
}

/**
 * 复制文本
 * @param {String} text 
 */
function copyText(text) {
	uni.setClipboardData({
		data: text, //要被复制的内容
		success: () => { //复制成功的回调函数
			uni.showToast({ //提示
				title: '复制成功'
			})
		}
	});
}



/**
 * 检查一个时间是否在某个时间段内1为在中间，0在开始时间前，2在结束时间后
 * @param {Date} checkTime 
 * @param {Date} startTime 
 * @param {Date} endTime 
 */
function checkTimeBetween(checkTime, startTime, endTime) {
	checkTime = new Date(checkTime).getTime();
	startTime = new Date(startTime).getTime();
	endTime = new Date(endTime).getTime();
	if (checkTime > startTime && checkTime < endTime) {
		return 1
	}
	if (checkTime < startTime) {
		return 0
	}
	if (checkTime > endTime) {
		return 2
	}
}


/**
 * 拷贝对象
 * @param {Object} obj 
 */
function copyObj(obj) {
	return JSON.parse(JSON.stringify(obj));
}


/**
 * 保存图片
 * @param {*} filePath 
 */
function saveImage(filePath) {


	uni.downloadFile({
		url: filePath,
		success({
			tempFilePath
		}) {
			console.log(tempFilePath)
			//#ifdef H5
			let a = document.createElement('a')
			a.setAttribute('download', "")
			a.setAttribute('href', tempFilePath)
			document.body.appendChild(a);
			a.style.display = 'none'
			a.click()
			document.body.removeChild(a)
			//#endif
			//#ifndef H5
			uni.saveImageToPhotosAlbum({
				filePath: tempFilePath,
				success() {
					uni.showToast({
						icon: "success",
						title: "保存成功"
					})
				},
				fail(err){
					console.log(123123)
				}
			})
			//#endif
		}

	})

}


/**
 * 保存文件
 * @param {*} filePath 
 */
function saveFile(filePath) {
	//#ifdef H5
	let a = document.createElement('a')
	a.setAttribute('download', "")
	a.setAttribute('href', filePath)
	document.body.appendChild(a);
	a.style.display = 'none'
	a.click()
	document.body.removeChild(a)
	uni.showToast({
		title:"保存成功"
	})
	//#endif
	//#ifndef H5
		let {platform}=uni.getSystemInfoSync()
		if(platform=='ios'){ //ios直接打开文档
			uni.openDocument({
				filePath:filePath
			})
		}else{
			uni.saveFile({
				tempFilePath:filePath,
				success(res) {
					uni.showToast({
						title:"保存成功"
					})
				}
			})
		}
		
	//#endif
}

/**
 * 转换为中文数字
 * @param {*} num 
 */
function toChineseNumber(num) {
	let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
	let unit = ['', '十', '百', '千', '万']
	num = parseInt(num)
	let getWan = (temp) => {
		let strArr = temp.toString().split('').reverse()
		let newNum = ''
		let newArr = []
		strArr.forEach((item, index) => {
			newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index])
		})
		let numArr = []
		newArr.forEach((m, n) => {
			if (m !== '零') numArr.push(n)
		})
		if (newArr.length > 1) {
			newArr.forEach((m, n) => {
				if (newArr[newArr.length - 1] === '零') {
					if (n <= numArr[numArr.length - 1]) {
						newNum += m
					}
				} else {
					newNum += m
				}
			})
		} else {
			newNum = newArr[0]
		}

		return newNum
	}
	let overWan = Math.floor(num / 10000)
	let noWan = num % 10000
	if (noWan.toString().length < 4) {
		noWan = '0' + noWan
	}
	return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}



/**
 * 日期格式化
 * @param {*} date 
 * @param {*} fmt 
 */
function formatDate(date, fmt) {
	date = new Date(date)
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}



/**
 * 选择文件
 */
function chooseFile() {
	return new Promise((resolve, reject) => {
		//#ifdef H5
		uni.chooseFile({
			count: 1,
			success(res) {
				let file = res.tempFiles[0]
				let ext = getFileNameExt(file.name)
				let path = file.path;
				resolve({
					ext,
					path,
					name: file.name
				})
			}
		})
		//#endif
		//#ifdef APP
		let sysInfo = uni.getSystemInfoSync()
		if (sysInfo.platform == 'android') {
			let AfDocument = uni.requireNativePlugin("Aq-ChooseFile");
			AfDocument.openMode({
				size: 1,
				paths: ['/storage/emulated/0/Download', '/storage/emulated/0/A', ], //自定义选择目录
				isDown: true, //是否下钻（true 筛选当前目录以下的所有文件，fales 只筛选当前目录文件） 
				types: [{
					name: '文档',
					value: ["doc", "wps", "docx", "xls", "xlsx", "pdf"]
				}, {
					name: '图片',
					value: ['jpg', 'png']
				}]
			}, ({
				code,
				res
			}) => {
				if (code == 'success') {
					resolve({
						name: res[0].name,
						path: res[0].path,
						ext: res[0].type
					})
				} else {
					resolve()
				}
			})
		} else {

		}
		//#endif
	})

}

/**
 *获取网络视频信息 
 * @param {*} originUrl 
 */
function getVideoSize(originUrl){
	return new Promise((resolve,reject)=>{
		uni.downloadFile({
			url:OssUrl+originUrl,
			success({tempFilePath}){
				uni.getVideoInfo({
					src:tempFilePath,
					success(res){
						resolve(res);
					},
					fail() {
						reject("获取视频信息失败")
					}
				})
			},
			fail() {
				reject('文件下载失败')
			}
		})
	})
}


/**
 * 获取网络图片信息
 * @param {*} originUrl 
 */
function getImageSize(originUrl){
	return new Promise((resolve,reject)=>{
		uni.downloadFile({
			url:OssUrl+originUrl,
			success({tempFilePath}){
				uni.getImageInfo({
					src:tempFilePath,
					success(res){
						resolve(res);
					},
					fail() {
						reject("获取图片信息失败")
					}
				})
			},
			fail() {
				reject('文件下载失败')
			}
		})
	})
}


/**
 * 获取分页状态
 * @param {*} param0 
 * @param {*} param1 
 */
function getPageLoadingStatus({page,list_rows},{last_page,total}){
	if(last_page==0||total==0){
		return 'empty'
	}
	if(page>=last_page){
		return 'nomore'
	}else{
		return 'none'
	}
}

/**
 * base64加密
 */
function base64Encode(str){
	return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
	function toSolidBytes(match, p1) {
		return String.fromCharCode('0x' + p1);
	}));
}

/**
 * base64解密
 * 
 */
function base64Decode(str){
	return decodeURIComponent(atob(str).split('').map(function (c) {
	return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
	}).join(''));
}

// 登录成功返回上一页
function loginSuccessBack(){
	let pages = getCurrentPages();
	let filArry = ['pages/login/login','pages/login/register','pages/login/forgetPwd','pages/login/verification','pages/login/setPwd']
	let newPage = pages.filter(item=>{
		return !filArry.includes(item.route)
	})
	
	
	if(newPage.length>0){
		
		setTimeout(()=>{
			uni.navigateBack()
		},1500)
	}else{
		setTimeout(()=>{
			uni.switchTab({ url:"/pages/index/index" })
		},1500)
	}
}

// 近两年年月数据
function getTwoYears() {
	let currentDate = new Date(); // 获取当前日期
	let startYear = currentDate.getFullYear() - 2; // 获取两年前的年份
	let startMonth = 1; // 开始的月份为1月
	let currentYear = currentDate.getFullYear(); // 获取当前年份
	let currentMonth = currentDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
	
	let result = []; // 存储结果的数组
	
	for(let y=startYear; y<=currentYear; y++){
	  let endMonth = y === currentYear ? currentMonth : 12; // 到当前年的月份为当前月，否则为12月
	  for(let m=startMonth; m<=endMonth; m++){
	    let yearMonth = `${y}-${m}`;
	    result.push({name:yearMonth,value:yearMonth});
	  }
	}
	return result.reverse()
}


// import forge from 'node-forge'
// import {KJUR,KEYUTIL } from 'jsrsasign'
import JSEncrypt from 'jsencrypt' 

function encode(obj){
	return new Promise((resolve,reject)=>{
		try{
			let publicPem=atob(secret);
			const encryptor = new JSEncrypt()
			encryptor.setPublicKey(publicPem);
			resolve(encryptor.encrypt(JSON.stringify(obj)))
		}catch(e){
			reject('err')
		}
	})
}




export default {
	getSimpleText,
	getFileNameExt,
	copyText,
	checkTimeBetween,
	saveImage,
	copyObj,
	saveFile,
	toChineseNumber,
	formatDate,
	chooseFile,
	getImageSize,
	getVideoSize,
	getPageLoadingStatus,
	checkPhone,
	base64Encode,
	base64Decode,
	loginSuccessBack,
	getTwoYears,
	encode
}
